import gc
import machine
import network
import time
from machine import Pin
from GPIO import *
from display import *
from config import *


def connect_wlan(ssid, password):
    
    WIFI_LED=Pin(46, Pin.OUT) #初始化WIFI指示灯
    wlan = network.WLAN(network.STA_IF)
    wlan.active(False)
    time.sleep(1)
    wlan.active(True)
    
    start_time=time.time()              #记录时间做超时判断
    if not wlan.isconnected():
        print('connecting to network...')
        pagecontrol.clear()
        pagecontrol.addline("    ")
        pagecontrol.addlinecn("正在连接无线网络")
        pagecontrol.nextshow()


        config = read_config()
        wlan.connect(config['wifi']['ssid'],config['wifi']['password']) #输入WIFI账号密码
        while not wlan.isconnected():
            WIFI_LED.value(1)
            time.sleep_ms(300)
            WIFI_LED.value(0)
            time.sleep_ms(300)
            if time.time()-start_time > 15 :
                wlan_if=1
                print('connect WiFi TIME OUT!\n')
                #超时退出
                return False
            
    WIFI_LED.value(1)
    print('network information:', wlan.ifconfig())    
    return True

pagecontrol =None
config = read_config()

if config['bootflag'] ==1:
    gc.collect()
    power = Pin(ppower, Pin.OUT) #电源开关
    power.value(0)
    #初始化液晶屏显示模块
    _display =display()                                                                                     
    #自动换页模块    
    pagecontrol =PageControl(_display)
    pagecontrol.clear()
    pagecontrol.addline("    ")
    pagecontrol.addlinecn("自动更新程序")
    pagecontrol.nextshow()


    # Wi-Fi credentials
    SSID =config['wifi']['ssid']
    PASSWORD =config['wifi']['password']
    
    if(connect_wlan(SSID, PASSWORD)):
        # Install Senko from PyPi
        #upip.install("micropython-senko")
        import senko
        
        OTA1 = senko.Senko(user="yangyugw", repo="micropython-ota", working_dir="", inpagecontrol=pagecontrol, files=["filesconfig.json"])
        if OTA1.update():
            print("updated to filesconfig")
            
        filesconfig = read_filesconfig()
        print(filesconfig)        
        OTA = senko.Senko(user="yangyugw", repo="micropython-ota", working_dir="", inpagecontrol=pagecontrol, files=filesconfig['filesname'])
        
        if OTA.update():
            print("Updated to the latest version!")
            config['bootflag']=0     
            write_config(config)
            machine.reset()        
    print("Boot completed")
    config['bootflag']=0     
    write_config(config)
    gc.collect()

